﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.SqlClient;
using System.Data.Common;
using System.DirectoryServices;
using System.Web.Hosting;

public partial class MasterPage : System.Web.UI.MasterPage
{
    Microsoft.Practices.EnterpriseLibrary.Data.Database db = DatabaseFactory.CreateDatabase("Application_Data");

    protected void Page_Init()
    {
        using (HostingEnvironment.Impersonate())        

        if (Session["sUser"] == null)
        {
            System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent();
            string[] strLoginName = Context.User.Identity.Name.Split('\\');

            Session["sLoginDomain"] = strLoginName[0].ToString();
            Session["sLogin"] = strLoginName[1].ToString();
            Session["sFullUserName"] = ADHelper.GetFullName(strLoginName[0].ToString(),strLoginName[1].ToString());
            Session["sEMailAddress"] = ADHelper.GetEMailAddress(strLoginName[0].ToString(), strLoginName[1].ToString());
        }

        if (Session["sTimeZone"] == null)
        {
            string results = "0";
            results = db.ExecuteScalar(CommandType.Text, "SELECT Count(*) FROM [User] Where UserNetworkLogin = '" + Session["sLogin"].ToString() + "'").ToString();
            
            if (results == "0")
            {
                Session["sTimeZone"] = "";
                Session["sPreviousPage"] = Page.AppRelativeVirtualPath.ToString();
                Response.Redirect(@"~/TimeZoneSet.aspx", false);
            }
            else
            {
                Session["sTimeZone"] = db.ExecuteScalar(CommandType.Text, "SELECT TimeZoneDisplayName FROM [User] Where UserNetworkLogin = '" + Session["sLogin"].ToString() + "'").ToString();
            }
        }        

        if (Session["sHTTP_PATH"] == null)
        {
            Session["sHTTP_PATH"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='HTTP_PATH'").ToString();
        }

        if (Session["sLogo"] == null)
        {
            Session["sLogo"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='logolocation'").ToString();
        }

        if (Session["sHTTP_PATH"] == null)
        {
            Session["sHTTP_PATH"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='HTTP_PATH'").ToString();
        }

        if (Session["sAdministrator"] == null)
        {
            string connectionString = ConfigurationManager.AppSettings["Application_DataConnString"];

            SqlConnection conn = new SqlConnection(connectionString);
            SqlDataAdapter a = new SqlDataAdapter(@"select UserNetworkID,UserNetworkLogin From [User] Where isAdmin = 'True'", conn);
            
            DataSet s = new DataSet();
            a.Fill(s);

            Hashtable myHashtable = new Hashtable();

            foreach (DataRow dr in s.Tables[0].Rows)
            {
                myHashtable.Add(dr["UserNetworkID"].ToString(),dr["UserNetworkLogin"].ToString().ToUpper());
            }
            
            if (myHashtable.ContainsValue(Session["sLogin"].ToString().ToUpper()))
            {
                Session["sAdministrator"] = true;
                Session["sRole"] = "Administrator";
            }
            else
            {
                Session["sAdministrator"] = false;
                Session["sRole"] = "User";
            }
        }      

        if (Session["sFooterText"] == null)
        {
            Session["sFooterText"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='FooterText'").ToString();
        }

        if (Session["sVersionApp"] == null)
        {
            Session["sVersionApp"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='VersionApp'").ToString();
        }

        if (Session["sTime1Display"] == null)
        {
            Session["sTime1Display"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time1DisplayName'").ToString();
        }
        if (Session["sTime2Display"] == null)
        {
            Session["sTime2Display"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time2DisplayName'").ToString();
        }
        if (Session["sTime3Display"] == null)
        {
            Session["sTime3Display"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time3DisplayName'").ToString();
        }
        if (Session["sTime4Display"] == null)
        {
            Session["sTime4Display"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time4DisplayName'").ToString();
        }
        if (Session["sTime1Time"] == null)
        {
            Session["sTime1Time"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time1TimeZoneID'").ToString();
        }
        if (Session["sTime2Time"] == null)
        {
            Session["sTime2Time"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time2TimeZoneID'").ToString();
        }
        if (Session["sTime3Time"] == null)
        {
            Session["sTime3Time"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time3TimeZoneID'").ToString();
        }
        if (Session["sTime4Time"] == null)
        {
            Session["sTime4Time"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='Time4TimeZoneID'").ToString();
        }        
        if (Session["sAppName"] == null)
        {
            Session["sAppName"] = db.ExecuteScalar(CommandType.Text, "SELECT ConfigValue FROM Config Where ConfigName ='AppName'").ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
     {
        this.lblFullName.NavigateUrl = "~/UserDetail.aspx?UserDomain=" + Session["sLoginDomain"].ToString() + "&UserNetworkLogin=" + Session["sLogin"].ToString();
        this.txtSearch.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + this.btnSearch.UniqueID + "').click();return false;}} else {return true}; ");

        if (Convert.ToBoolean(Session["sAdministrator"].ToString()) == true)
        {
            this.lnkSiteAdmin.Visible = true;
            this.lnkSiteAdmin.Enabled = true;
        }
        else
        {
            this.lnkSiteAdmin.Visible = false;
            this.lnkSiteAdmin.Enabled = false;
        }      


        DateTimeOffset nowDateTime = DateTimeOffset.Now;
        DateTimeOffset Time1DateTime = TimeZoneInfo.ConvertTime(nowDateTime, TimeZoneInfo.FindSystemTimeZoneById(Session["sTime1Time"].ToString()));
        DateTimeOffset Time2DateTime = TimeZoneInfo.ConvertTime(nowDateTime, TimeZoneInfo.FindSystemTimeZoneById(Session["sTime2Time"].ToString()));
        DateTimeOffset Time3DateTime = TimeZoneInfo.ConvertTime(nowDateTime, TimeZoneInfo.FindSystemTimeZoneById(Session["sTime3Time"].ToString()));
        DateTimeOffset Time4DateTime = TimeZoneInfo.ConvertTime(nowDateTime, TimeZoneInfo.FindSystemTimeZoneById(Session["sTime4Time"].ToString()));

        this.lblTimeZone.Text = Session["sTimeZone"].ToString();
        this.txtSearch.Attributes.Add("onfocus", "this.value = ''");
        this.lblFooter.Text = "About " + Session["sFooterText"].ToString() + " " + Session["sVersionApp"].ToString(); 
        this.lblTime1Name.Text = Session["sTime1Display"].ToString();
        this.lblTime2Name.Text = Session["sTime2Display"].ToString();
        this.lblTime3Name.Text = Session["sTime3Display"].ToString();
        this.lblTime4Name.Text = Session["sTime4Display"].ToString();
        this.lblTime1.Text = Time1DateTime.DateTime.ToShortTimeString();
        this.lblTime2.Text = Time2DateTime.DateTime.ToShortTimeString();
        this.lblTime3.Text = Time3DateTime.DateTime.ToShortTimeString();
        this.lblTime4.Text = Time4DateTime.DateTime.ToShortTimeString();
        this.lblFullName.Text = Session["sFullUserName"].ToString();
        this.lblRole.Text = Session["sRole"].ToString();
        this.imgLogo.ImageUrl = Session["sLogo"].ToString();  
    } 
    protected void btnSearch_Click(object sender, ImageClickEventArgs e)
    {
        if (this.txtSearch.Text.ToUpper() == "SEARCH" | this.txtSearch.Text.Length < 3)
        {
            MessageBox.Show("Invalid Search criteria");
        }
        else
        {
            Response.Redirect(@"~/SearchResults.aspx?SearchText=" + this.txtSearch.Text.ToString());
        }
    }
}
